<template>
  <view class="news_card_main" v-if="loading===false">
    <view class="news_card_title">最近播放动态</view>
    <view class="news_card_items">
      <el-scrollbar height="400px" view-class="scrview">
        <el-timeline style="max-width: 300px;width: 98%;display: flex;flex-direction: row;flex-wrap: wrap">
          <el-timeline-item
              v-for="(activity, index) in NewsData.data"
              :key="index"
              size="large"
              :timestamp="activity.time"
          >
            {{ activity.user }} 用户播放：{{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </el-scrollbar>
    </view>
  </view>
  <view v-else>
    Loading
  </view>
</template>
<style>
.news_card_main
{
  display: flex;
  max-width: 250px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  flex-wrap: wrap;
  flex-direction: row;
}
.news_card_title
{
  width: 100%;
  display: flex;
  height: 30px;
  background-color: white;
}
.news_card_items
{
  margin-top: 10px;
  display: flex;
}
.scrview
{
  display: flex;
  width: 100%;
  justify-content: center;
}
</style>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import {ElMessage} from "element-plus";
import router from "@/router";

const NewsData = ref({ data: [] });
const loading = ref(true);

const fetchData = async () => {
  const formData = new FormData();
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch("https://movie.cpb2013.top/admin/views.php?mode=get_video_news", {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
      },
      body: formData,
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();
    if (data.status === 'success') {
      NewsData.value = data;
    }
    else if (data.status === 'danger') {
      localStorage.removeItem('key');
      ElMessage.error(data.msg);
      await router.push('/login'); // Use router to navigate to the login page
    }
  } catch (error) {
    console.error('There was a problem with the fetch operation:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>